import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:travel/chat/chat_flutter.dart';
import 'package:travel/chat/utils/chat_view_item_record_body_type/chat_view_item_record_body_type.dart';
import 'package:travel/chat/utils/parameter_model_set/parameter_model_set.dart';
import 'package:travel/chat/widgets/chat_view_item/chat_view_item.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:url_launcher/url_launcher.dart';

class ChatController extends GetxController with WidgetsBindingObserver {
  ChatViewItemAvatarModel rightAvatar = ChatViewItemAvatarModel(
      avatarSize: 40.w,
      avatarPath:
          'https://img2.baidu.com/it/u=1403316214,3492494261&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500');

  ChatViewItemAvatarModel leftAvatar = ChatViewItemAvatarModel(
    avatarSize: 40.w,
    avatarPath:
        'https://img1.baidu.com/it/u=3547412726,2113146789&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  );

  FocusNode focusNode = FocusNode();

  List<ChatViewItem> data = [];

  late ChatViewWidgetController chatViewWidgetController;

  RxString word = ''.obs;

  RxDouble bottom = 0.0.obs;

  @override
  void onInit() {
    WidgetsBinding.instance.addObserver(this);
    data.add(ChatViewItem(
      itemBody: '您好，客服小姐姐，在吗？',
      avatarModel: rightAvatar,
      backgroundColor: ColorsUtils.rgba(251, 223, 202, 1),
      textTypeModel: ChatViewItemTextTypeModel(
          itemBodyTextStyle:
              StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000)),
    ));
    data.add(
        ChatViewItem(senderRight: false, itemBody: '我在的亲，请问有什么需要帮助的吗？', avatarModel: leftAvatar));
    super.onInit();
  }

  void onCreated(ScrollController chatViewWidgetListViewController,
      ChatViewWidgetController chatViewWidgetController) {
    this.chatViewWidgetController = chatViewWidgetController;
    // 模拟发送消息
    Future.delayed(const Duration(seconds: 1), () {
      chatViewWidgetController.add(ChatViewItem(
          senderRight: false,
          itemBodyType: ChatViewItemRecordBodyType.image,
          itemBody: 'https://pic35.photophoto.cn/20150511/0034034892281415_b.jpg',
          avatarModel: leftAvatar));
      chatViewWidgetController.add(ChatViewItem(
        senderRight: false,
        avatarModel: leftAvatar,
        customRecordTimeWidget: const Align(
          alignment: Alignment.center,
          child: Text('2023-12-13'),
        ),
        customRecordTimeStyle:
            StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 12.sp),
        itemBody: '带记录时间',
      ));
      chatViewWidgetController.add(ChatViewItem(
        avatarModel: rightAvatar,
        itemBodyType: ChatViewItemRecordBodyType.image,
        itemBody: 'https://pic35.photophoto.cn/20150511/0034034892281415_b.jpg',
        imageTypeModel: ChatViewItemImageTypeModel(
          previewImageLongPressMenu: const ['保存'],
          onPreviewImageTapMenu: (data, index, menuList) {
            debugPrint("$data $index $menuList");
          },
          // customPreviewImageCallback:(imagePath) {
          //     print(imagePath);
          // },
          // customLongPress:(context) {
          //     print('customLongPress');
          // },
        ),
      ));
    });
  }

  void onSend() {
    chatViewWidgetController.add(ChatViewItem(
      itemBody: word.value,
      avatarModel: rightAvatar,
      backgroundColor: ColorsUtils.rgba(251, 223, 202, 1),
      textTypeModel: ChatViewItemTextTypeModel(
          itemBodyTextStyle:
              StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000)),
    ));
    word.value = '';
  }

  @override
  void didChangeMetrics() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      bottom.value = MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first)
          .viewInsets
          .bottom;
    });
    super.didChangeMetrics();
  }

  @override
  void onClose() {
    focusNode.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }
}

class ChatView extends GetView<ChatController> {
  const ChatView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
      appBar: AppBar(
        automaticallyImplyLeading: true,
        leading: InkWell(
          onTap: Get.back,
          child: Icon(
            Icons.arrow_back_ios,
            color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
            size: 20.w,
          ),
        ),
        leadingWidth: 40.w,
        title: Text(
          '联系客服',
          style: StylesUtils.customTextStyle(
              color: ColorsUtils.color3333, fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
        actions: [
          IconButton(
              onPressed: () {
                launchUrl(Uri(scheme: 'tel', path: '10086'));
              },
              icon: Icon(
                Icons.phone,
                size: 18.sp,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
              ))
        ],
      ),
      body: buildBody(context),
      resizeToAvoidBottomInset: false,
      bottomNavigationBar: Obx(() => Padding(
            padding: EdgeInsets.only(bottom: controller.bottom.value),
            child: Container(
              height: 50.h,
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              decoration: const BoxDecoration(color: Colors.white),
              child: Row(
                children: [
                  Expanded(
                      child: TextField(
                    focusNode: controller.focusNode,
                    controller: ToolsUtils.editingController(controller.word.value),
                    cursorWidth: 2.0,
                    cursorRadius: const Radius.circular(2),
                    cursorColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                    style:
                        StylesUtils.customTextStyle(fontSize: 15.sp, color: ColorsUtils.color3333),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15),
                        borderSide: BorderSide.none,
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15),
                        borderSide: BorderSide.none,
                      ),
                      hintText: '请输入你要咨询问题',
                      contentPadding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                      isCollapsed: true,
                      isDense: true,
                      fillColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF8f8),
                      filled: true,
                      hintStyle: StylesUtils.customTextStyle(
                          color: ColorsUtils.color9999, fontSize: 15.sp),
                    ),
                    onChanged: (String keyword) {
                      controller.word.value = keyword;
                    },
                  )),
                  Align(
                    child: TextButton(
                        onPressed: controller.onSend,
                        child: Text(
                          '发送',
                          style: StylesUtils.customTextStyle(
                              fontSize: 16.sp, color: ColorsUtils.color3333),
                        )),
                  )
                ],
              ),
            ),
          )),
    );
  }

  Widget buildBody(BuildContext context) {
    return GestureDetector(
      onTap: () {
        controller.focusNode.unfocus();
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        child: ChatViewWidget(
          isNeedScrollBottom: true,
          isOpenPreviewImage: true,
          onCreated: controller.onCreated,
          children: controller.data,
        ),
      ),
    );
  }
}
